package com.hangzhou.xyj.ui.fragment.base;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.net.listener.HttpResponseListener;
import com.hangzhou.xyj.ui.dialog.LoadingDialog;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.List;


/**
 * fragment公共基类
 *
 * @author neo.duan
 */
public abstract class BaseFragment extends Fragment {
    public final String TAG = getClass().getSimpleName();
    public Context mContext;
    private CommonTitleBarView mLlTop;
    private SwipeRefreshLayout mRefreshLayout;
    private TextView mTvFailure;
    private boolean mErrorViewEnable = true; //错误页面是否可用
    private LoadingDialog mLoadingDialog;
    private MyTextView mTvNoDataTip;//没有数据的时候 提示文本

    private RelativeLayout mRlLoadingAnim;//加载动画区域
    private ImageView mIvLoadingAnim;//动画
    private AnimationDrawable animation;
    private boolean isLoadingAnimShow;//加载动画是否可见

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContext = getActivity();
        return inflater.inflate(R.layout.activity_base, null);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        initBaseView();
        initBaseListeners();

        /***初始化标题栏****/
        initTop();
        /***初始化内容布局****/
        initLayouts();
        /***初始化内容view****/
        initViews();
        /***初始化事件监听****/
        initListeners();
        /***初始化数据****/
        initDatas();
        super.onViewCreated(view, savedInstanceState);
    }

    /**
     * 基类View初始化
     */
    private void initBaseView() {
        mRlLoadingAnim = findView(R.id.rl_loading_anim);
        mIvLoadingAnim = findView(R.id.iv_loading_anim);
        mLlTop = findView(R.id.title_id_root);
        mRefreshLayout = findView(R.id.content_id_root);
        mTvFailure = findView(R.id.content_id_failure);
        mTvNoDataTip = findView(R.id.mtv_nodata_tip);

        //设置默认下拉刷新不可用
        mRefreshLayout.setEnabled(false);
    }

    /**
     * 是否显示加载动画
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/6/12 15:06
     */
    protected void setLoadingAnimVisible(boolean animVisible) {
        animation = (AnimationDrawable) mIvLoadingAnim.getBackground();
        if (animVisible) {
            mRlLoadingAnim.setVisibility(View.VISIBLE);
            animation.start();
            isLoadingAnimShow = true;
        } else {
            mRlLoadingAnim.setVisibility(View.GONE);
            animation.stop();
            isLoadingAnimShow = false;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (animation != null && animation.isRunning()) {//销毁动画
            animation.stop();
        }
    }

    /**
     * 初始化基类事件
     */
    private void initBaseListeners() {
        //点击重试
        mTvFailure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doRefresh();
            }
        });
        //下拉刷新
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                doRefresh();
            }
        });
    }

    /**
     * 重新加载：默认initData,如果不需要initData，可以重写该方法
     */
    public void doRefresh() {
        initDatas();
    }

    public void setContentView(int layoutResID) {
        View contentView = View.inflate(getActivity(), layoutResID, null);
        mRefreshLayout.addView(contentView);
    }

    public void setContentView(View contentView) {
        mRefreshLayout.addView(contentView);
    }

    /**
     * 设置没有数据的时候 提示文本
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/4/25 16:00
     */
    public void setNoDataTip(boolean enable, String text) {
        if (enable) {
            mTvNoDataTip.setText(text.trim());
            mTvNoDataTip.setVisibility(View.VISIBLE);
        } else {
            mTvNoDataTip.setVisibility(View.GONE);
        }
    }

    /**
     * 是否显示顶部导航
     *
     * @param enabled
     */
    public void enableTop(boolean enabled) {
        mLlTop.setVisibility(enabled ? View.VISIBLE : View.GONE);
    }


    /**
     * 是否显示左导航键
     *
     * @param enabled
     */
    public void enableBack(boolean enabled) {
        mLlTop.enableBack(enabled);
    }

    public void enableBack(boolean enabled, Drawable drawable) {
        mLlTop.enableBack(enabled, drawable);
    }

    public void enableRightNav(boolean enabled) {
        mLlTop.enableRightNav(enabled);
    }

    public void enableRightNav(boolean enabled, int resId) {
        mLlTop.enableRightNav(enabled, resId);
    }

    public void enableRightNav(boolean enabled, String rightNav) {
        mLlTop.enableRightNav(enabled, rightNav);
    }

    /**
     * 设置标题
     *
     * @param enabled
     * @param title
     */
    public void enableTitle(boolean enabled, String title) {
        mLlTop.enableTitle(enabled, title);
    }

    public void enableTitle(boolean enabled, int resId) {
        mLlTop.enableTitle(enabled, resId);
    }

    /**
     * 是否显示网络错误页面
     *
     * @param enable
     */
    public void enableNetErrorView(boolean enable) {
        this.mErrorViewEnable = enable;
        mTvFailure.setEnabled(enable);
    }

    /**
     * 显示网络错误View
     */
    private void showNetErrorView(boolean show) {
        //设置了网络错误页面不可用，do nothing
        if (!mErrorViewEnable) {
            return;
        }
        mTvFailure.setVisibility(show ? View.VISIBLE : View.GONE);
        mRefreshLayout.setVisibility(show ? View.GONE : View.VISIBLE);
    }

    /**
     * 下拉刷新是否可用
     *
     * @param enabled
     */
    public void enableRefresh(boolean enabled) {
        mRefreshLayout.setEnabled(enabled);
    }

    /**
     * 显示加载框
     */
    public void showLoadingDialog() {
        showLoadingDialog(null);
    }

    /**
     * 显示加载框
     *
     * @param text 文本
     */
    public void showLoadingDialog(String text) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(mContext);
        }

        //2个有一个show，则可以
        if (mLoadingDialog.isShowing() || mRefreshLayout.isRefreshing()) {
            return;
        }
        if (StringUtil.isNotBlank(text)) {
            mLoadingDialog.setLoadText(text);
        }
        mLoadingDialog.show();
    }

    /**
     * 隐藏加载框
     */
    public void hideLoadingDialog() {
        if (mRefreshLayout != null && mRefreshLayout.isRefreshing()) {
            mRefreshLayout.setRefreshing(false);
        }
        if (mLoadingDialog == null) {
            return;
        }
        if (mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    /**
     * 关闭父Fragment加载框：用于ViewPager多个页面，子页面关闭父Fragment的Loading
     */
    public void hideParentLoadingDialog() {
        FragmentManager manager = getFragmentManager();
        List<Fragment> fragments = manager.getFragments();
        if (fragments == null || fragments.isEmpty()) {
            return;
        }
        //遍历Fragment，hideLoadingDialog
        for (Fragment fragment : fragments) {
            if (fragment != null && fragment instanceof BaseFragment) {
                ((BaseFragment) fragment).hideLoadingDialog();
            }
        }
    }

    public abstract void initTop();

    /**
     * 初始化视图
     */
    public abstract void initLayouts();

    /**
     * 初始化视图
     */
    public abstract void initViews();

    /**
     * 初始化数据
     */
    public abstract void initDatas();

    /**
     * 初始化监听器
     */
    public abstract void initListeners();

    @SuppressWarnings("unchecked")
    public <T extends View> T findView(int id) {
        return (T) getView().findViewById(id);
    }

    /**
     * 注册EventBus
     */
    public void registerEventBus() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    /**
     * 注销EventBus
     */
    public void unRegisterEventBus() {
        EventBusUtil.unregister(this);
    }

    /**
     * 用于Http请求的监听器
     */
    public abstract class MyHttpResponseListener extends HttpResponseListener {

        @Override
        public void onStart() {
            if (!isLoadingAnimShow)//显示加载动画的时候，不显示加载对话框
                showLoadingDialog();
            showNetErrorView(false);
        }

        @Override
        public void onFail(String msg) {
            hideLoadingDialog();
            hideParentLoadingDialog();
            if (StringUtil.isNotBlank(msg)) {
                ToastUtil.show(msg);
            }
            if (isLoadingAnimShow) {
                setLoadingAnimVisible(false);//异常加载动画 不可见
            }
        }

        @Override
        public void onSuccess(Object model) {
            hideLoadingDialog();
        }

        @Override
        public void onDone(String msg) {
            hideLoadingDialog();
            hideParentLoadingDialog();
            if (isLoadingAnimShow) {
                setLoadingAnimVisible(false);//异常加载动画 不可见
            }
            if (StringUtil.isNotBlank(msg)) {
                ToastUtil.show(msg);
            }
            showNetErrorView(true);
        }

        @Override
        public void onError() {
            hideLoadingDialog();
            hideParentLoadingDialog();
            if (isLoadingAnimShow) {
                setLoadingAnimVisible(false);//异常加载动画 不可见
            }
            ToastUtil.show(getResources().getString(R.string.tip_net_error));
            showNetErrorView(true);
        }
    }
}
